#!/bin/sh

FILE="INTERNE-output.csv"
EXPORT_FILE="run.sql"
FW_NAME="FWSM_INTERNE"
RULE_NAME="0"

OUT01=$(mktemp /tmp/fwsm.XXXXXXXXXX) || { echo "Failed to create temp file"; exit 1;}
OUT02=$(mktemp /tmp/fwsm.XXXXXXXXXX) || { echo "Failed to create temp file"; exit 1;}
OUT03=$(mktemp /tmp/fwsm.XXXXXXXXXX) || { echo "Failed to create temp file"; exit 1;}
OUT04=$(mktemp /tmp/fwsm.XXXXXXXXXX) || { echo "Failed to create temp file"; exit 1;}
OUT05=$(mktemp /tmp/fwsm.XXXXXXXXXX) || { echo "Failed to create temp file"; exit 1;}

if [ -f $FILE ]; then
        echo "$FILE exist, continu ..."
        echo "Substitution des virgules"
        sed "s/,/','/g" $FILE > $EXPORT_FILE

        echo "Suppression de la dernière colonne"
        awk -F, '{print "FWSM_INTERNE\047,\0470\047,\047"$1","$2","$3","$4","$5","$6","$7","$8","$9","$10","$11","$12","$13}' $EXPORT_FILE > $OUT01

        echo "Ajout en début de ligne"
        sed -i "s/^/('','/" $OUT01

        echo "Ajout en fin de ligne"
        sed -i "s/$/),/" $OUT01

        echo "Suppression des espaces"
        sed -i "s/ ','',/','',/g" $OUT01
        sed -i "s/extended /extendted/g" $OUT01
        sed -i "s/,' ', /,'',/g" $OUT01

        echo "Suppression des apostrophes"
        sed -i "s/d'acces/d acces/" $OUT01

        echo "Suppression de la première ligne"
        sed -i '1d' $OUT01

        echo "ajout de l'entête"
        sed -i 1i'INSERT INTO `acl` (`id`, `fw_name`, `rule_num`, `name`, `line`, `type`, `function`, `protocol`, `src_net`, `src_port`, `dst_net`, `dst_port`, `time`, `inactive`, `log`, `remark`) VALUES' $OUT01

        echo "suppression du mot host"
        sed -i "s/host //g" $OUT01

        echo "Remplacement de la dernière virgule par un point virgule"
        sed -i "$ s/,$/;/" $OUT01

        echo "Préparation du fichier"
        mv $OUT01 $EXPORT_FILE


        echo "Done !"

else
echo "'$FILE' not found !"
fi